<?php
/** [字段逻辑模型]
 * @Author: 976123967@qq.com
 * @Date:   2015-01-09 17:38:09
 * @Last Modified by:   chenli
 * @Last Modified time: 2015-03-05 23:28:10
 */
class FieldLogic extends Model{


	protected 	$tableName = 'model_field';
	public $model;
	private $cache;



	/**
	 * [_initialize 初始化]
	 * @return [type] [description]
	 */
	public function _initialize()
	{
		$this->model = D('Field');
		$this->cache = S('field');
	}






	/**
	 * [$_validate 自动验证]
	 * @var array
	 */
	protected $_validate = array(
		array('title','require','请输入字段说明',1,'regex',3),
		array('title','check_title','字段说明已经存在',1,'callback',3),
		array('fname','require','请输入字段名称',1,'regex',3),
		array('fname','/^[a-z][a-z0-9_]*$/i','字段名称必须以字母开头并且只能包含字母或者数字或者下划线',1,'regex',3),
		array('fname','check_fname','字段名称已经存在',1,'callback',3),
		array('sort','require','请输入排序值',1,'regex',3),
		array('sort','/^\d+$/i','排序值只能是数字',1,'regex',3),
	);


	/**
	 * [check_title 检查字段说明是否重复]
	 * @param  [type] $con [description]
	 * @return [type]      [description]
	 */
	protected function check_title($con)
	{
		$mid = I('post.mid');
		$fid = I('post.fid');
		if($fid)
			$where['fid'] = array('neq',$fid);
		$where['title'] = $con;
		$where['model_mid'] = $mid;
		$data = $this->where($where)->find();
		if($data)
			return false;

		return true;
	}
	/**
	 * [check_fname 检查字段是否重复]
	 * @param  [type] $con [description]
	 * @return [type]      [description]
	 */
	protected function check_fname($con)
	{


		// 验证是否和主表的字段名称重复
		if(in_array($con, S('mainFieldsName')))
			return false;

		// 验证是否和当前模型附表表的字段名称重复
		$mid = I('post.mid');
		$fid = I('post.fid');
		if($fid)
			$where['fid'] = array('neq',$fid);
		$where['fname'] = strtolower($con);
		$where['model_mid'] = $mid;
		$data = $this->where($where)->find();
		if($data)
			return false;

	
		
		return true;
	}


	/**
	 * [$_auto 自动完成]
	 * @var array
	 */
	protected $_auto = array(
		array('model_mid','_mid',3,'callback'),
		array('fname','strtolower',3,'function'),
	);

	/**
	 * [_mid mid自动完成]
	 * @return [type] [description]
	 */
	protected function _mid()
	{
		return  I('post.mid');
	}

	
	/**
	 * [get_all_by_model_mid 读取字段通过mid]
	 * @param  [type] $mid [description]
	 * @return [type]      [description]
	 */
	public function get_all_by_model_mid($mid)
	{
		$data = $this->cache[$mid];
		if(!$data) return false;
		foreach($data as $k=>$v)
		{
			$data[$k]['system']  = $v['is_system']?"√":"×";
			$data[$k]['disabled'] = !$v['is_disabled']?"√":"×";
			$data[$k]['lists']    = $v['show_lists']?"√":"×";

			switch ($v['show_type']) 
			{
				case 1: //文本框
					$data[$k]['show_type_name']='文本框';
					break;
				case 2: //多行文本框
					$data[$k]['show_type_name']='多行文本框';					
					break;
				case 3: //完整编辑器
					$data[$k]['show_type_name']='完整编辑器';
					break;
				case 4: //简单编辑器
					$data[$k]['show_type_name']='简单编辑器';
					break;
				case 5: //单选框
					$data[$k]['show_type_name']='单选框';
					break;
				case 6: //下拉框
					$data[$k]['show_type_name']='下拉框';
					break;
				case 7: //多选框
					$data[$k]['show_type_name']='多选框';
					break;
				case 8: //文件上传
					$data[$k]['show_type_name']='文件上传';
					break;
				case 9: //图片上传
					$data[$k]['show_type_name']='图片上传';
				case 10:
					$data[$k]['show_type_name']= '地区联动';
					break;
			}
			$data[$k]['show_type_name'] = $v['is_system']?'系统':$data[$k]['show_type_name'];
		}
		
		return $data;
	}

	/**
	 * [get_all_field_name_by_model_mid 读取字段通过mid]
	 * @param  [type] $mid [description]
	 * @return [type]      [description]
	 */
	public function get_all_field_name_by_model_mid($mid)
	{
		$data   = $this->get_all_by_model_mid($mid);
		if(!$data) return false;
		$result = array();
		foreach($data as $k=>$v)
		{
			$result[] = $v['fname'];
		}
		
		return $result;
	}

	/**
	 * [get_all_attachment_field_name_by_model_mid 读取附件字段通过mid]
	 * @param  [type] $mid [description]
	 * @return [type]      [description]
	 */
	public function get_all_attachment_field_name_by_model_mid($mid)
	{
		$data   = $this->get_all_by_model_mid($mid);
		if(!$data) return false;
		$result = array();
		foreach($data as $k=>$v)
		{
			if($v['show_type'] == 8 || $v['show_type'] == 9)
				$result[] = $v['fname'];
		}
		
		return $result;
	}

	/**
	 * [update_cache 更新缓存]
	 * @return [type] [description]
	 */
	public function update_cache()
	{

		// 主表所有字段名称 缓存
		$mainFields = $this->query('SHOW COLUMNS FROM `'.C('DB_PREFIX').'article`');
		$mainFieldsName = array();
		if($mainFields)
		{
			foreach($mainFields as $v)
			{
				$mainFieldsName[] =$v['Field'];
			}

		}
		S('mainFieldsName',$mainFieldsName);


		
		// 所有附表字段缓存 按照模型mid 缓存
		$data = $this->order('sort asc,fid desc')->select();
	
		$modelFieldValueModel = D('ModelFieldValue');
		$temp = array();
		if($data)
		{
			foreach($data as $k=>$v)
			{
				$v['field_value'] = $modelFieldValueModel->where(array('field_fid'=>$v['fid']))->select();
				$temp[$v['model_mid']][$v['fid']]=$v;
			}
		}

		S('field',$temp);
	} 

	/**
	 * [operation 处理批量操作]
	 * @return [type] [description]
	 */
	public function operation()
	{
		$fid  = I('post.fid');
		switch (true) 
		{
			// 排序
			case isset($_POST['update_sort']):
				$sort = I('post.sort');
				foreach($fid as $k=>$v)
				{
					$this->array(array('sort'=>$sort[$k],'fid'=>$v));
				}
				$msg= '排序成功';
				break;
			
			default:
				$this->error = '操作选择错误';
				return false;

		}
		// 更新缓存
		$this->update_cache();
		return $msg;
	}

	/**
	 * [add_field 添加字段]
	 */
	public function add_field()
	{
		
		if(!$this->create())
			return false;
		// 添加
		$fid = $this->add();


		// 修改表结构
		$mid = I('post.mid');
		// 表名称
		$tables 	= D('Model','Logic')->get_all();
		$table 		= isset($tables[$mid]['name'])?$tables[$mid]['name']:'';
		if(!$table)
		{
			$this->error = '表不存在';
			return false;
		}
		$table 		= C('DB_PREFIX').'article_'.$table;
		
		$fname = I('post.fname');
		$title = I('post.title');
		$type = $this->get_type(I('post.show_type'));

		$this->model->alter_add_field(array('table'=>$table,'fname'=>$fname,'type'=>$type,'title'=>$title));

		



		// 字段默认值
		$fieldValue = I('post.field_value');
		if($fieldValue)
		{
			$modelFieldValueModel = D('ModelFieldValue');
			foreach($fieldValue as $v)
			{
				$data[] = array(

					'field_fid'=>$fid,
					'field_value'=>$v,
				);
			}
			$modelFieldValueModel->addAll($data);
		}
		// 更新缓存
		$this->update_cache();
		return true;
	}


	/**
	 * [get_type 更具字段展示类型返回字段类型]
	 * @return [type] [description]
	 */
	public function get_type($showType)
	{	
		// 类型
		switch ($showType) {
			case 1:
				$type = 'varchar';

				break;
			case 2:
				$type = 'varchar';

				break;
			case 3:
				$type = 'text';

				break;
			case 4:
				$type = 'text';
				break;
			case 5:
				$type = 'varchar';
				break;
			case 6:
				$type = 'varchar';
				break;
			case 7:
				$type = 'varchar';
				break;
			case 8:
				$type = 'varchar';
				break;
			case 9:
				$type = 'varchar';
				break;
			case 10:
				$type = 'varchar';
				break;
		}
		return $type;

	}


	/**
	 * [find_one 查找一条记录]
	 * @return [type] [description]
	 */
	public function find_one()
	{
		$fid   = I('get.fid');
		$mid   = I('get.mid');
		$field = $this->cache[$mid];
		if(!$field)
		{
			$this->error = '字段不存在';
			return false;
		}
		foreach($field as $k=>$v)
		{
			if($k==$fid)
				return $v;
		}
		$this->error = '字段不存在';
		return false;
	}


	/**
	 * [update_field 更新字段]
	 * @return [type] [description]
	 */
	public function update_field()
	{
		if(!$this->create())
			return false;
	
		$fid = I('post.fid');
		$mid 		= I('post.mid');

		
		/***修改表结构**/
		// 表名称
		$tables 	= D('Model','Logic')->get_all();
		$table 		= isset($tables[$mid]['name'])?$tables[$mid]['name']:'';
		if(!$table)
		{
			$this->error = '表不存在';
			return false;
		}
		$table 		= C('DB_PREFIX').'article_'.$table;

		// 旧字段名称
		$oldfname 	= isset($this->cache[$mid][$fid]['fname'])?$this->cache[$mid][$fid]['fname']:'';
		if(!$oldfname)
		{
			$this->error = '字段不存在';
			return false;
		}

		$fname 		= I('post.fname');
		$title 		= I('post.title');
		$type 		= $this->get_type(I('post.show_type'));

		$this->model->alter_edit_field(array('table'=>$table,'oldfname'=>$oldfname,'fname'=>$fname,'type'=>$type,'title'=>$title));

		/***更新数据**/
		// 更新
		$this->save();

		
		
		// 删除原先的值
		$modelFieldValueModel = D('ModelFieldValue');
		$modelFieldValueModel->where(array('field_fid'=>$fid))->delete();

		// 字段默认值
		$fieldValue = I('post.field_value');
		if($fieldValue)
		{
			
			foreach($fieldValue as $k=>$v)
			{
				$data = array(

				'field_fid'=>$fid,
				'field_value'=>$v,

				);

				$key = explode('-', $k);
				if(isset($key[0]))
				{
					$data['fv_id']=$key[0];
				}
	
				$modelFieldValueModel->add($data);
			}
		}
		// 更新缓存
		$this->update_cache();



		return true;
	}

	/**
	 * [del_field 删除字段]
	 * @return [type] [description]
	 */
	public function del_field()
	{
		$fid = I('get.fid');
		$mid   = I('get.mid');


		/***更改表结构***/
		// 表名称
		$tables 	= D('Model','Logic')->get_all();
		$table 		= isset($tables[$mid]['name'])?$tables[$mid]['name']:'';
		if(!$table)
		{
			$this->error = '表不存在';
			return false;
		}
		$table 		= C('DB_PREFIX').'article_'.$table;

		// 字段名称
		$fname = isset($this->cache[$mid][$fid]['fname'])?$this->cache[$mid][$fid]['fname']:'';
		if(!$fname)
		{
			$this->error = '字段不存在';
			return false;
		}
		$this->model->drop_field(array('table'=>$table,'fname'=>$fname));

		/***删除数据***/
		$this->delete($fid);
		D('ModelFieldValue')->where(array('field_fid'=>$fid))->delete();

		// 更新缓存
		$this->update_cache();

		return true;
	}



}